$(function() {
    var app;
    _.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g,      // print value: {{ value_name }}
        evaluate    : /\{%([\s\S]+?)%\}/g,   // excute code: {% code_to_execute %}
        escape      : /\{%-([\s\S]+?)%\}/g
    }; // excape H
    app = {
        pageIndex: [0, 0, 0, 0, 0],
        pageInfoIndex:[0],
        page: 15,
        tabIndex: 0,
        ajaxLoading: true,
        infoListData:[],
        picListData : [],
        infoDate:[],
        angle : 0,
        photoIndex : 0,
        isBind : true,
        initialize: function() {
            this.initDomNode();
            this.bindEvents();
            this.requestUserCity();
            $('#datepicker').datepicker({
              language: "zh-CN",
              weekStart: 7,
              todayHighlight: true,
              autoclose: true
            });
        },
        initDomNode: function() {
            this.box = $('#infoSearch');
            this.resultBox = $('.result-box', this.box);
            this.searchBtn = $('.info-search-btn', this.box);
            this.sellerName = $('.seller-name', this.box);
            this.sellerCity = $('.seller-city', this.box);	
            this.clientName = $('.client-name', this.box);	
            this.picTimeStart = $('.pic-time-start', this.box);	
            this.picTimeEnd = $('.pic-time-end', this.box);	
            this.infoListTable = $('.info-list-table', this.box);
            this.pageInfoTable = $('.page-info-table', this.box);
            this.pageStatis = $('.page-statis', this.box);
            this.picList = $('.pic-list', this.box);
            this.loading = $('#dataLoading');
            this.cityList = $('#city-list');
            this.confirmCity = $('#confirm-city');
            this.cityBtn = $('#city-list-btn');
            this.popup = $('#myModal');
            this.schemeTab = $('.scheme-tab', this.box);
        },
        bindEvents: function() {
            var that;
            that = this;
            this.searchBtn.on('click', function() { //执行案搜索菜单
                that.loading.show();
                that.infoListTable.empty();
                that.resultBox.addClass('hide fade');
                that.requestInfoList(true);
            });
            this.infoListTable.on('click', '.rm-info-btn', function(e){
            	e.preventDefault();
                that.loading.show();
            	that.rmInfo($(this).data('id'));
            });
            this.pageInfoTable.on('click', function(e){
            	var index;
            	e.preventDefault();
            	index = that.pageInfoIndex[0];
				$(this).hasClass('prev') ? index-- : index++;
				if(index <0){
					index = 0;
					alert('亲，已经是第一页了！');
				}
				if(index > that.pages){
					index = that.pages;
					alert('亲，已经是最后一页了!');
				}
				that.pageInfoIndex[0] = index;
				that.navToPage();
            });
            this.infoListTable.on('click', '.view-pic-btn', function(e){
                var id;
                id = $(this).data('id');
                that.loading.show();
            	that.requestPicList(id);
                that.searchId = id;
            });

            this.picList.on('click', 'a', function(e){
                e.preventDefault();
                that.angle = 0;
                that.photoIndex = $(this).closest('li').index();
                $('img', that.popup).css({
                    WebkitTransform : 'rotate(0deg)',
                    MozTransform : 'rotate(0deg)',
                    MsTransform : 'rotate(0deg)',
                    OTransform : 'rotate(0deg)',
                    transform : 'rotate(0deg)'
                });
                that.popup.find('img').prop('src', $(this).children('img').prop('src'));
            });
            this.popup.on('click', 'a', function(e){
                var action;
                e.preventDefault();
                action = $(this).data('action');
                action = action.replace(/^\w/, function(str){
                    return str.toUpperCase();
                });
                that['pic'+action] && that['pic'+action]();
            });

            this.schemeTab.on('click', 'a', function(e) { //图片类型Tab切换
                e.preventDefault();
                that.switchTab($(this));
            });

            this.picList.on('click', '.rm-pic', function() { //删除图片
                that.loading.show();
                that.removePic($(this).data('id'));
            });

            this.sellerCity.on('focus', function(){
                that.cityBtn.trigger('click');
            });
            this.confirmCity.on('click', function(){
                that.setCityVal();
            });

            $(window).scroll(function(){
                that.loadMoreCase();
            });
        },
        sendToServer: function(opt) {
            var base, url, type, that;
            that = this;
            base = 'http://218.89.135.237:9000/API/WEB/';
            url = base + opt.apiName;
            type = opt.type ? opt.type : 'GET';
            $.ajax({
                type: type,
                url: url,
                async: true,
                data: opt.data,
                // timeout: 15000,
                dataType: 'json'
            }).done(function(data) {
                // console.log(data);
                if (data.IsSuccessfully) {
                    opt.success && opt.success(data);
                } else {
                    opt.error && opt.error(data);
                    alert(data.ErrorMessage);
                }
                that.loading.hide();
            }).fail(function(xhr, ajaxOptions, thrownError) {
                // console.log(arguments);
                that.loading.hide();
                alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
            });
        },
        verFormData:function(){
        	var status, data;
        	status = true;
        	data =  this.getFormData();
        	for(var item in data){
        		if(item == 'city' || item == 'clientName' || item == 'startDate' ||  item == 'endDate'){
        			continue;
        		}
        		status = status && data[item] != '';
        	}
        	return status;
        },
        getFormData:function(){
        	var startDate, endDate;
        	startDate = $.trim(this.picTimeStart.val());
        	endDate = $.trim(this.picTimeEnd.val());        	
        	return {
        		salesCompanyName : $.trim(this.sellerName.val()),
	        	city : $.trim(this.sellerCity.val()),
		        clientName : $.trim(this.clientName.val()),
		        startDate :  this.formatTime(startDate),
		        endDate : this.formatTime(endDate)
        	}
        },
        formatTime:function(str){
        	var arr;
        	arr = [];
        	if(str == ''){
        		return;
        	}
        	arr = str.split(/\D/);
        	arr.splice(3,1);
        	return arr.join('-');
        },
        requestInfoList:function(isTrigger){
        	var opt, data;
            if(isTrigger){
                if(!this.verFormData()){
                    alert('经销商名称不能为空！');
                    this.loading.hide();
                    return;
                }
            }
        	data = this.getFormData();
            this.initData = data;
        	this.infoDate = [data.startDate, data.endDate];
        	opt = {
        	    apiName: 'ClientManagement/SearchClientInfo.ashx',
        	    data: data,
        	    success: this.infoListSuccess.bind(this)
        	};

        	this.sendToServer(opt);
        },
        infoListSuccess:function(data){
        	this.infoTablePaging(data); //分页
        	this.infoListTable.html(_.template($('#infoListTableTmpl').html(), {
        		ImportClients: this.infoListData[0][0]
        	}));
        	this.pageIndex = [0];
        	this.upatePageStatis();
            this.resultBox.removeClass('hide fade');
        },
        upatePageStatis:function(){
        	this.pageStatis.html('第'+(this.pageInfoIndex[0] +1) +'页 共'+(this.pages+1)+'页');
        },
        navToPage:function(){
        	this.infoListTable.html(_.template($('#infoListTableTmpl').html(), {
        		ImportClients: this.infoListData[0][this.pageInfoIndex[0]]
        	}));
        	this.upatePageStatis();
        },
        rmInfo:function(id){
        	var opt;
        	opt = {
        	    apiName: 'ClientManagement/DeleteClientInfo.ashx',
        	    data: {clientMaterialID : id},
        	    success: this.rmInfoSuccess.bind(this)
        	};
        	this.sendToServer(opt);
        },
        rmInfoSuccess: function(data){
        	alert('删除操作已成功！');
            this.requestInfoList();
        },
        infoTablePaging:function(data){
        	this.handleInfoTablePaging(data.ImportClients, 0);
        },
        handleInfoTablePaging:function(data, index){
        	var arr, result, page;
        	arr = [];
        	result = [];
        	page = 5;
        	if (!data) {
        	    return;
        	}
        	for (var i = 0, l = data.length; i < l;) {
        	    arr.push(data[i]);
        	    i++;
        	    if (i % page == 0 || i == l) {
        	        result.push(arr);
        	        arr = [];
        	    }
        	}
        	this.pages = result.length - 1 ; //此处从0开始计算
        	// console.log(result);
        	this.infoListData[index] = result;
        },
        requestPicList:function(id){
        	var opt;
            id = id || this.searchId;
        	opt = {
        	    apiName: 'ClientManagement/GetSingleClientPictures.ashx',
        	    data: {
        	    	clientMaterialID : id,
        	    	startDate : this.infoDate[0],
        	    	endDate : this.infoDate[1]
        	    },
        	    success: this.picListSuccess.bind(this)
        	};
            this.picList.empty();
        	this.sendToServer(opt);
        },
        picListSuccess: function(data){
        	this.groupPicList(data);
        	this.picList.html(_.template($('#picListTmpl').html(), {
        	    initIndex : 0,
				ClientPictures: this.picListData[0][0]
        	}));
        	this.pageIndex = [0, 0, 0, 0, 0];
            this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
        },
        groupPicList:function(data){ //分组图片数据
        	var arr;
        	arr = [[], [], [], [], []];
        	_.each(data.ClientPictures, function(item){
        		arr[item.PictureType].push(item);
        	});
        	// console.log(arr);
        	// this.picListData = arr;
        	this.paging(arr);
        },
        paging: function(data) {
            this.handlePaging(data[0], 0);
            this.handlePaging(data[1], 1);
            this.handlePaging(data[2], 2);
            this.handlePaging(data[3], 3);
            this.handlePaging(data[4], 4);
        },
        handlePaging:function(data, index){
            var arr, result, page;
            arr = [];
            result = [];
            page = this.page;
            if (!data) {
                return;
            }
            for (var i = 0, l = data.length; i < l;) {
                arr.push(data[i]);
                i++;
                if (i % page == 0 || i == l) {
                    result.push(arr);
                    arr = [];
                }
            }
            // console.log(result);
            this.picListData[index] = result;
        },
        setSchemeSummary: function(str) {
            var arr, kv, data, key, val;
            arr = [];
            key = [];
            val = [];
            if (str != null && str != '') {
                arr = str.split(',');
                for (var i = 0, l = arr.length; i < l; i++) {
                    kv = arr[i].split(':');
                    key.push(kv[0]);
                    val.push(kv[1]);
                }
            }
            data = {
                key: key,
                val: val
            };
            this.schemeSummary.html(_.template($('#schemeSummaryTmpl').html(), data));
        },
        getCheckedPic: function() {
            var arr, pic, status;
            arr = [];
            pic = [];
            status = false;
            $('input:checked', this.schemeList).each(function(index, item) {
                arr.push($(item).val());
                pic.push($(item));
                status = !status ? $(item).data('status') == '已审核' : status;
            });
            // console.log(arr);
            this.checkedPic = pic;
            this.checkedPicStatus = status;
            return arr;
        },
        removePic: function(id) {
            var opt;
            opt = {
                apiName: 'ClientManagement/DeletePicture.ashx',
                data: {
                    pictureID: id
                },
                success: this.removePicSuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        removePicSuccess: function(data) {
            alert('成功删除图片！');
            this.requestPicList();
        },
        switchTab: function(target) {
            var index, arr;
            index = target.parent().index();
            // this.photoIndex=0;
            if(!this.picListData[0]){
                return;
            }
            target.parent().addClass('active').siblings().removeClass('active');
            this.tabIndex = index;
            this.pageIndex[index] = 0; 
            this.picList.html(_.template($('#picListTmpl').html(), {
                initIndex : 0,
                ClientPictures: this.picListData[index][0]
            }));

        },
        loadMoreCase:function(){
            var scrollBottom;
            scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
            if(scrollBottom < 50){
                // if(this.ajaxLoading){
                //     return;
                // }
                // this.ajaxLoading = true;
                // console.log('xxx');
                this.pageIndex[this.tabIndex]++;
                this.renderPage();
                // this.ajaxLoading = false;
            }
        },
        renderPage:function(){
            var index, data, len;
            index = this.pageIndex[this.tabIndex];
            data = this.picListData[this.tabIndex] && this.picListData[this.tabIndex][index];
            if(!data){
                return;
            }
            len = this.picList.find('.span3').length;
            this.picList.append(_.template($('#picListTmpl').html(), {initIndex:len, ClientPictures:data}));
        },
        picTurnLeft:function(){
            this.angle-=45;
            this.turnPic();
        },
        picTurnRight:function(){
            this.angle+=45;
            this.turnPic();
        },
        turnPic:function(){
            // console.log(this.angle);
            $('img', this.popup).css({
                WebkitTransform : 'rotate('+this.angle+'deg)',
                MozTransform : 'rotate('+this.angle+'deg)',
                MsTransform : 'rotate('+this.angle+'deg)',
                OTransform : 'rotate('+this.angle+'deg)',
                transform : 'rotate('+this.angle+'deg)'
            });
        },
        picPrev:function(){
            if(this.photoIndex<=0){
                alert('亲，已经是第一张图片了');
                return;
            }
            this.photoIndex-=1;
            this.picShow();
        },
        picNext:function(){
            if(this.photoIndex>=this.picList.find('li').length-1){
                alert('亲，已经是最后一张图片了');
                return;
            }
            this.photoIndex+=1;
            this.picShow();
        },
        picShow:function(){
            var src;
            src = this.picList.find('li').eq(this.photoIndex).find('img').prop('src');
            this.popup.find('img').prop('src', src);
        },
        requestUserCity:function(){
            var opt;
            opt = {
                apiName: 'ClientManagement/GetUserOperationCities.ashx',
                success: this.userCitySuccess.bind(this)
            };
            this.sendToServer(opt);
        },
        userCitySuccess:function(data){
            this.cityList.html(_.template($('#cityListTmpl').html(), data));
        },
        setCityVal: function(){
            var arr;
            arr = [];
            this.cityList.find(':checked').each(function(){
                arr.push($(this).val());
            });
            this.sellerCity.val(arr.join(','));
        }
    };
    app.initialize();
    return app;
});